package com.lu.manage.core.aop;

import com.lu.manage.core.common.exception.SysLogExcepetion;
import com.lu.manage.core.tips.ErrorTip;
import com.lu.manage.core.utils.StringUtil;
import org.apache.shiro.authc.CredentialsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import static com.lu.manage.core.utils.HttpContext.getRequest;

/**
 * @program LuBoot
 * @description: 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 * @author: zhanglu
 * @create: 2019-11-03 21:59:00
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 账号密码错误异常
     */
    @ExceptionHandler(CredentialsException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String credentials(CredentialsException e, Model model) {
        String username = getRequest().getParameter("username");
        model.addAttribute("tips", "账号密码错误");
        return "/login.html";
    }


    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorTip errorTip(Exception e){
        System.out.println("----------------------LuBoot系统异常----------------------");
        e.printStackTrace();
        return new ErrorTip();
    }

    @ExceptionHandler(SysLogExcepetion.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorTip errorTip(SysLogExcepetion e){
        System.out.println("----------------------LuBoot系统异常记录日志----------------------");
        String message = StringUtil.errorMessage(e);
        StackTraceElement[] stackTraces = e.getStackTrace();
        if(stackTraces != null){
            StackTraceElement stackTrace = stackTraces[0];
            String className = stackTrace.getClassName();
            String method = stackTrace.getMethodName();
        }
        return new ErrorTip();
    }

}
